import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import Home from '../views/Home.vue'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "Login" */ '../views/Login.vue')
  },
  {
    path: '/entry',
    name: 'entry',
    meta: { requiresAuth: true },
    component: () => import(/* webpackChunkName: "Entry" */ '../views/Entry.vue')
  },
  {
    path: '/statistics',
    name: 'statistics',
    redirect:'/analysis',
    component: () => import(/* webpackChunkName: "Statistics" */ '../views/Statistics.vue'),
    children: [
      {
        path: '/analysis',
        name: 'analysis',
        meta: { requiresAuth: true },
        component: () => import(/* webpackChunkName: "AnalysisInfo" */ '../views/AnalysisInfo.vue')
      },
      {
        path: '/userInfo',
        name: 'userInfo',
        meta: { requiresAuth: true },
        component: () => import(/* webpackChunkName: "UserInfo" */ '../views/UserInfo.vue')
      },
      {
        path: '/roomInfo',
        name: 'roomInfo',
        meta: { requiresAuth: true },
        component: () => import(/* webpackChunkName: "RoomInfo" */ '../views/RoomInfo.vue')
      },
      {
        path: '/statisticsInfo',
        name: 'statisticsInfo',
        meta: { requiresAuth: true },
        component: () => import(/* webpackChunkName: "StatisticsInfo" */ '../views/StatisticsInfo.vue')
      },
    ]
  },
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})


//判断是否登录
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth) {
      //这里判断用户是否登录，验证本地存储是否有sessionStorage
      if (!localStorage.getItem('userName')) { // 判断当前的sessionStorage是否存在
          next({
              path: '/login',
              // query: { redirect: from.fullPath } //登录成功后重定向到当前页面
          })
      } else {
          next()
      }
  } else {
      next() // 确保一定要调用 next()
  }
})

export default router
